<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // const url = "https://example.com/?age=128&name=Jonathan";
      // let params = new URLSearchParams(url.substring(1));
      // let params = new URLSearchParams("age=128&name=Jonathan");
      // let name = params.get("name"); // is the string "Jonathan"
      // let age = parseInt(params.get("age"), 10); // is the number 18
      // const ads = params.entries();
      // const ad = Object.create(ads);
      // const ff = {};
      // for (var pair of params.entries()) {
      //   ff[pair[0]] = pair[1];
      // }
      // console.log(ff, ff.age, ff.name);

      function getParams(name, url) {
        if (url && typeof url !== "string") {
          console.error("url must be of string type");
          return null;
        }

        let params = {};

        if (!url) {
          params = new URL(window.location.href).searchParams;
        } else if (url.startsWith("http")) {
          params = new URL(url).searchParams;
        } else if (url.startsWith("?")) {
          params = new URLSearchParams(url.substring(1));
        } else {
          params = new URLSearchParams(url);
        }

        const res = {};
        for (var pair of params.entries()) {
          try {
            res[pair[0]] = decodeURIComponent(pair[1]);
          } catch (error) {
            res[pair[0]] = "";
          }
        }

        if (name) {
          return res[name];
        }

        return res;
      }
      let url = "https://stackabuse.com/search?q=devpoint&page=1";
      // url = "age=128&name=Jonathan";
      const res = getParams("", url);
      console.log(res);
    </script>
  </body>
</html>
